/**
 * Utility functions for demo management
 * 
 * This file is managed by Git and reads data from public/demos.json
 * Last updated: 2025-08-21
 */
import { getRelatedFiles, getFileType, parseVueFile } from './codeParser.js';

// 从public/demos.json获取演示数据
let demoFilePaths = {};

// 异步加载demos.json数据
async function loadDemoFilePaths() {
  try {
    const response = await fetch('/demos.json');
    const demosJson = await response.json();
    const demosList = demosJson.demos || [];
    
    // 构建demoFilePaths对象
    demosList.forEach(demo => {
      demoFilePaths[demo.id] = demo.component;
    });
  } catch (error) {
    console.error('Failed to load demos.json:', error);
    demoFilePaths = {};
  }
}

// 初始化加载数据
loadDemoFilePaths();

/**
 * Get the source code of a demo file
 * @param {string} demoId - The ID of the demo
 * @returns {Promise<string>} - The source code of the demo
 */
export async function getDemoSourceCode(demoId) {
  const filePath = demoFilePaths[demoId];
  if (!filePath) {
    throw new Error(`Demo with ID "${demoId}" not found`);
  }

  try {
    // Use fetch API to get the raw file content from the public directory
    const response = await fetch(filePath);
    if (!response.ok) {
      throw new Error(`Failed to fetch source code: ${response.status} ${response.statusText}`);
    }
    return await response.text();
  } catch (error) {
    console.warn(`Could not load source code for ${filePath}:`, error);
    return `// Error loading source code for ${demoId}
// File path: ${filePath}
// Error: ${error.message}`;
  }
}

/**
 * Get all source code files related to a demo
 * @param {string} demoId - The ID of the demo
 * @returns {Promise<Array>} - Array of file objects with name, content and type
 */
export async function getAllDemoSourceFiles(demoId) {
  const relatedFiles = getRelatedFiles(demoId);
  const files = [];
  
  for (const file of relatedFiles) {
    try {
      const response = await fetch(file.path);
      if (!response.ok) {
        throw new Error(`Failed to fetch source code: ${response.status} ${response.statusText}`);
      }
      const content = await response.text();
      
      // 如果是 Vue 文件，解析为 template、script、style 三个部分
      if (file.type === 'vue') {
        const parsed = parseVueFile(content);
        // 将每个部分作为独立的文件对象添加到列表中
        if (parsed.template) {
          files.push({
            name: `${file.name} (Template)`,
            content: parsed.template,
            type: 'html'
          });
        }
        if (parsed.script) {
          files.push({
            name: `${file.name} (Script)`,
            content: parsed.script,
            type: 'javascript'
          });
        }
        if (parsed.style) {
          files.push({
            name: `${file.name} (Style)`,
            content: parsed.style,
            type: 'css'
          });
        }
      } else {
        // 非 Vue 文件直接添加
        files.push({
          name: file.name,
          content,
          type: file.type || getFileType(file.name)
        });
      }
    } catch (error) {
      console.warn(`Could not load source code for ${file.path}:`, error);
      files.push({
        name: file.name,
        content: `// Error loading source code for ${file.name}
// File path: ${file.path}
// Error: ${error.message}`,
        type: file.type || getFileType(file.name)
      });
    }
  }
  
  return files;
}